#include "udptest.h"
#include <QHostAddress>
#include <QNetworkDatagram>
#include <QDebug>
#include <QThread>
#include <iostream>

UdpTest::UdpTest(QObject *parent) : QObject(parent)
{
    UdpTest(QString("114.115.153.2"));
}

UdpTest::UdpTest(QString IPAddress, QObject *parent) : QObject(parent), m_sending(false), m_sendSpeed(1), m_count(0)
{
    p_soc = new QUdpSocket(this);
    if(!p_soc->bind(QHostAddress(IPAddress), 4664))
    {
        qDebug() << "绑定出错，错误信息：" << p_soc->errorString();
        return ;
    }
    qDebug().noquote() << "绑定成功，本地地址：" << p_soc->localAddress().toString();
    connect(p_soc, &QUdpSocket::readyRead, this, &UdpTest::receiveData);

    //设置持续数据发送
    QTimer *m_t = new QTimer(this);
    connect(m_t, &QTimer::timeout, this, &UdpTest::sendData);
    //m_t->setInterval(m_sendSpeed);
    m_t->start(1);
    for(int i = 0; i < 504; ++i)
    {
        m_testData.append(i & 0xff);
    }
}


void UdpTest::receiveData()
{
    while(p_soc->hasPendingDatagrams())
    {
        QNetworkDatagram data = p_soc->receiveDatagram();
        QString display;
        display += "收到来自[";
        display.append(data.senderAddress().toString() + ":" + QString::number(data.senderPort()));
        display += "]的数据：\n";
        display += data.data().toHex(' ');
        display += "\n";
        display += checkData(data.data()) ? "验证通过" : "验证失败";
        display += "\n";
        qDebug().noquote() << display;
        if(checkData(data.data()))
        {
            m_clientIP = data.senderAddress();
            m_clientPort = data.senderPort();
            qDebug() << "开始发送";
            m_sending = true;
            QThread::sleep(1);
            m_sending = false;
            qDebug() << "结束发送，总发送数据包数量：" << m_count;
            m_count = 0;
        }
    }
}


bool UdpTest::checkData(const QByteArray datas)
{
    int len = datas.length();
    quint16 cs = (quint8(datas.at(len - 2)) << 8) + quint8(datas.at(len - 1));
    return cs == qChecksum(datas, len - 2);
}

void UdpTest::sendData()
{
    //qDebug() << "sendData in";
    std::cout << "\rsendData in";
    if(m_sending)
    {
        ++m_count;
        QNetworkDatagram d(m_testData, m_clientIP, m_clientPort);
        p_soc->writeDatagram(d);
    }
}
